package org.example.verify;

import org.example.csv.CSVData;
import org.example.util.CSVUtils;
import org.example.util.FileUtils;
import org.junit.Test;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class Case2Verify {

    public static final String basicPath = "D:\\Development\\GeaFlowCompetition\\sf1\\snapshot";

    public static final String outputPath = "D:\\Development\\GeaFlowCompetition\\output";

    public static final String outputName = "result2-sf1-check.csv";

    Map<String, Integer> res = new HashMap<>();

    @Test
    public void verify() {
        Path path = FileUtils.pathJoin(basicPath, "AccountTransferAccount.csv");
        CSVData csvData = CSVUtils.read(path);

        List<String> fromList = csvData.getByColumn("fromId");
        List<String> toList = csvData.getByColumn("toId");

        Map<String, List<String>> pathMap = new HashMap<>();
        for (int i = 0; i < fromList.size(); i++) {
            String from = fromList.get(i);
            List<String> pathList = pathMap.getOrDefault(from, new ArrayList<>());
            pathList.add(toList.get(i));
            pathMap.put(from, pathList);
        }

        for (String key : pathMap.keySet()) {
            dfs(key, key, pathMap, 0);
        }

        for (String key : res.keySet()) {
            System.out.println("key = " + key + ", cnt = " + res.get(key));
        }

        CSVData writer = new CSVData(Arrays.asList("id", "value"));
        List<Long> ids = new ArrayList<>();
        for (String key : res.keySet()) {
            ids.add(Long.valueOf(key));
        }
        Collections.sort(ids);
        for (Long id : ids) {
            String key = String.valueOf(id);
            writer.addLine(new String[]{key, String.valueOf(res.get(key))});
        }
        CSVUtils.write(FileUtils.pathJoin(outputPath, outputName), writer);
    }

    private void dfs(final String start, String current, final Map<String, List<String>> pathMap, int u) {
        if (u >= 3) {
            if (Objects.equals(start, current)) {
                res.put(start, res.getOrDefault(start, 0) + 1);
            }
            return;
        }

        List<String> path = pathMap.getOrDefault(current, new ArrayList<>());
        for (String s : path) {
            dfs(start, s, pathMap, u + 1);
        }
    }
}
